<template>
  <el-dialog
    :model-value="drawerVisible"
    :destroy-on-close="true"
    :title="title"
    width="74%"
    top="10vh"
    draggable
    custom-class="user-info-dialog"
    :close-on-click-modal="false"
    @closed="handleClose"
    @close="handleClose"
  >
    <el-scrollbar height="65vh">
      <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="formData" label-position="top">
        <div class="startStep" v-show="stepPage === 1">
          <div class="all-h info-form">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="formData.name" placeholder="请填写项目名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="项目编号" prop="code">
              <el-input v-model="formData.code" placeholder="请填写项目编号" clearable></el-input>
            </el-form-item>
            <el-form-item label="项目类型" prop="typeId">
              <el-select v-model="formData.typeId" placeholder="请选择项目类型" clearable>
                <el-option v-for="item in getDict('projectTypeId')" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目经理" prop="userId">
              <el-select v-model="formData.userId" placeholder="请选择项目经理" clearable>
                <el-option v-for="item in viewUserList" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目描述" prop="description">
              <el-input v-model="formData.description" placeholder="请填写项目描述" clearable></el-input>
            </el-form-item>
            <el-form-item label="行业" prop="industryId">
              <el-select v-model="formData.industryId" placeholder="请选择行业" clearable>
                <el-option v-for="item in getDict('industry')" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户公司" prop="companyId">
              <el-select v-model="formData.companyId" placeholder="请选择客户公司" clearable @change="changeCompany">
                <el-option v-for="item in companyList" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="终端客户公司" prop="companyFinalId">
              <el-select
                v-model="formData.companyFinalId"
                placeholder="请选择终端客户公司"
                clearable
                @change="changeCompanyFinal"
              >
                <el-option v-for="item in companyList" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="国家" prop="countryId">
              <el-select v-model="formData.countryId" placeholder="请选择国家" clearable filterable @change="changeCountry">
                <el-option v-for="item in countryList" :key="item.countryName" :label="item.countryName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="所在地区" prop="addressed" v-if="!formData.countryId || formData.countryName === '中国'">
              <el-cascader v-model="formData.addressed" :options="areaList" clearable :props="defaultOptions" ref="cascaderRef" />
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请填写详细地址" clearable></el-input>
            </el-form-item>
            <el-form-item label="	硬件非标" prop="hardwareNonStandard">
              <el-switch v-model="formData.hardwareNonStandard" :inactive-value="false" :active-value="true" />
            </el-form-item>
            <el-form-item label="硬件非标定制内容" prop="hardwareContent">
              <el-input v-model="formData.hardwareContent" placeholder="请填写硬件非标定制内容" clearable></el-input>
            </el-form-item>
            <el-form-item label="硬件非标定制周期（天）" prop="hardwareCycle">
              <el-input-number
                v-model="formData.hardwareCycle"
                :min="0"
                :precision="0"
                placeholder="请填写硬件非标定制周期（天）"
              />
              <!-- <el-input v-model=""  clearable></el-input> -->
            </el-form-item>
            <el-form-item label="软件非标" prop="softwareNonStandard">
              <el-switch v-model="formData.softwareNonStandard" :inactive-value="false" :active-value="true" />
            </el-form-item>
            <el-form-item label="软件非标定制内容" prop="softwareContent">
              <el-input v-model="formData.softwareContent" placeholder="请填写软件非标定制内容" clearable></el-input>
            </el-form-item>
            <el-form-item label="软件非标定制周期（天）" prop="softwareCycle">
              <el-input-number
                v-model="formData.softwareCycle"
                :min="0"
                :precision="0"
                placeholder="请填写软件非标定制周期（天）"
              />
              <!-- <el-input v-model="formData.softwareCycle" placeholder="请填写软件非标定制周期（天）" clearable></el-input> -->
            </el-form-item>
            <!-- <el-form-item label="车辆数" prop="agvCount">
              <el-input v-model="formData.agvCount" placeholder="请填写车辆数" clearable></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="项目进度" prop="progressId">
              <el-select v-model="formData.progressId" placeholder="请选择项目进度" clearable>
                <el-option v-for="item in getDict('industry')" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="项目状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择项目状态" clearable>
                <el-option v-for="item in getDict('projectStatus')" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目状态描述" prop="statusDescription">
              <el-input v-model="formData.statusDescription" placeholder="请填写项目状态描述" clearable></el-input>
            </el-form-item>
            <el-form-item label="合同签订日期" prop="signContractTime">
              <el-date-picker
                v-model="formData.signContractTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择合同签订日期"
              />
            </el-form-item>
            <el-form-item label="计划开始时间" prop="planStartTime">
              <el-date-picker
                v-model="formData.planStartTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划开始时间"
              />
            </el-form-item>
            <el-form-item label="	计划结束时间" prop="planEndTime">
              <el-date-picker
                v-model="formData.planEndTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划结束时间"
              />
            </el-form-item>
            <el-form-item label="实际开始时间" prop="startTime">
              <el-date-picker
                v-model="formData.startTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择实际开始时间"
              />
            </el-form-item>
            <el-form-item label="实际结束时间" prop="endTime">
              <el-date-picker
                v-model="formData.endTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择实际结束时间"
              />
            </el-form-item>
          </div>
          <div class="fan">
            <div class="title">方案信息</div>
            <el-table
              :data="formData.planModels"
              border
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
              class="table"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="originalFileName" label="文件名称" />
              <el-table-column prop="typeId" label="文件类型" width="200">
                <template #default="scope">
                  <el-form-item
                    class="form-item"
                    :prop="'planModels.' + scope.$index + '.typeId'"
                    :rules="[{ required: true, message: '请选择文件类型', trigger: 'change' }]"
                  >
                    <el-select v-model="scope.row.typeId" placeholder="请选择文件类型" clearable>
                      <el-option v-for="item in getDict('fileTypeId')" :key="item.name" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click.prevent="deleteFA(scope.$index)"> 删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
            <Upload v-model:file-list="fileList" :prefix-data="PROJECT" @change="uploadChange" />
          </div>
        </div>
        <div v-show="stepPage === 2">
          <el-form-item label="项目模板" prop="templateId" v-if="!props.projectId">
            <el-select v-model="formData.templateId" placeholder="请选择项目模板" clearable @change="changeTemplate">
              <el-option v-for="item in templateAll" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <div class="title">里程碑节点设置</div>
          <el-table
            :data="formData.taskModels.filter(item => item.markerId)"
            border
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            class="table"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="序号" width="100">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="节点" />
            <el-table-column prop="name" label="任务节点时间">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.planEndTime"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择任务截止时间"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)"> 删除 </el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div v-show="stepPage === 1">
        <el-button @click="emit('update:drawer-visible', false)"> 取消 </el-button>
        <el-button @click="nextFn"> 下一步</el-button>
      </div>
      <div v-show="stepPage === 2">
        <el-button @click="previewFn"> 上一步</el-button>
        <el-button type="primary" @click="handleSubmit"> {{ props.projectId ? "编辑" : "创建" }} </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
// import { Plus } from "@element-plus/icons-vue";
import { ref, reactive, onMounted, onUnmounted, defineEmits } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useDict } from "@/hooks/useDict";
import { useAddress } from "@/hooks/useAddress";
import Upload from "@/components/Upload/upload.vue";
import { PROJECT } from "@/constants";
// api
import { getCompanyList } from "@/api/modules/customer";
import { getTemplateType, getTemplateTaskModel, addProject, getProjectDetail, updateProject } from "@/api/modules/project";
import { getListAllUser } from "@/api/modules/sys";
// hook
const { getDict } = useDict(["industry", "projectStatus", "projectTypeId", "fileTypeId"]);
const { countryList, defaultOptions, areaList } = useAddress();
// 初始化数据
const props = defineProps({ drawerVisible: { type: Boolean, default: false }, projectId: { type: String, default: "" } });
const emit = defineEmits(["update:drawer-visible", "change"]);
// 变量定义
let varTitle = ref(props.projectId ? "编辑" : "新增");
let title = ref(varTitle.value + "项目");
let formData = reactive({
  name: "",
  code: "",
  description: "",
  industryId: "",
  companyId: "",
  companyName: "",
  companyFinalId: "",
  companyFinalName: "",
  province: undefined,
  provinceCode: undefined,
  userId: "",
  city: undefined,
  cityCode: undefined,
  district: undefined,
  districtCode: undefined,
  countryId: undefined,
  countryName: undefined,
  addressed: [],
  address: "",
  typeId: "",
  hardwareNonStandard: false,
  hardwareContent: "",
  hardwareCycle: 0,
  softwareNonStandard: false,
  softwareContent: "",
  softwareCycle: 0,
  agvCount: "",
  progressId: "",
  status: "",
  signContractTime: "",
  planStartTime: "",
  planEndTime: "",
  startTime: "",
  endTime: "",
  templateId: "",
  statusDescription: "",
  planModels: [],
  taskModels: []
});
const rules = reactive({
  name: [{ required: true, message: "请填写项目名称" }],
  code: [{ required: true, message: "请填写项目编号" }],
  userId: [{ required: true, message: "请选择项目经理" }],
  typeId: [{ required: true, message: "请选择项目类型" }],
  planModels: [{ typeId: [{ required: true, message: "请选择文件类型", trigger: "change" }] }]
});
let companyList = reactive([]);
let templateAll = reactive([]);
let fileList = ref([]);
let stepPage = ref(1);
const cascaderRef = ref();
const ruleFormRef = ref();
const viewUserList = ref([]);
// 事件
const changeTemplate = async templateId => {
  if (templateId) {
    if (formData.taskModels.length) {
      ElMessageBox.confirm("确认切换模板吗?", "温馨提示", { type: "warning" }).then(async () => {
        const { data } = await getTemplateTaskModel({ templateId });
        formData.taskModels.splice(0, formData.taskModels.length, ...data);
      });
    } else {
      const { data } = await getTemplateTaskModel({ templateId });
      formData.taskModels.splice(0, formData.taskModels.length, ...data);
    }
  } else {
    if (formData.taskModels.length) {
      ElMessageBox.confirm("确认切换模板吗?", "温馨提示", { type: "warning" }).then(() =>
        formData.taskModels.splice(0, formData.taskModels.length)
      );
    } else {
      formData.taskModels.splice(0, formData.taskModels.length);
    }
  }
};
const uploadChange = data => {
  data = data.map(item => {
    item.typeId = "";
    return item;
  });
  formData.planModels.splice(formData.planModels.length, 0, ...data);
};
const changeCompany = item => {
  const companyLists = companyList.find(itm => itm.id === item);
  formData.companyName = companyLists?.name;
};
const changeCompanyFinal = item => {
  const companyLists = companyList.find(itm => itm.id === item);
  formData.companyFinalName = companyLists?.name;
};
const changeCountry = item => {
  const country = countryList.value.find(itm => itm.id === item);
  if (country?.countryName != "中国") {
    formData.addressed = [];
  }
  formData.countryName = country?.countryName;
};
const handleClose = () => {
  emit("update:drawer-visible", false);
};
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      // 省市区传值处理
      if (formData.addressed && formData.addressed.length) {
        let arrAddress = cascaderRef.value.getCheckedNodes();
        let names = arrAddress[0]["pathLabels"];
        let value = formData.addressed;
        formData.province = names[0];
        formData.provinceCode = value[0];
        formData.city = names[1];
        formData.cityCode = value[1];
        formData.district = names[2];
        formData.districtCode = value[2];
      }
      if (formData.planModels.length) {
        formData.planModels = formData.planModels.map(item => {
          return {
            typeId: item.typeId,
            name: item.name,
            originalFileName: item.originalFileName,
            path: item.path
          };
        });
      }

      delete formData.addressed;
      delete formData.templateId;

      props.projectId ? await updateProject(formData) : await addProject(formData);
      ElMessage.success({ message: props.projectId ? `修改项目成功！` : `添加项目成功！` });
      emit("update:drawer-visible", false);
      emit("change", true);
    } catch (error) {
      console.log(error);
    }
  });
};
const nextFn = () => {
  stepPage.value++;
  title.value = stepPage.value === 1 ? varTitle.value + "项目" : "里程碑节点确认";
};
const previewFn = () => {
  stepPage.value--;
  title.value = stepPage.value === 1 ? varTitle.value + "项目" : "里程碑节点确认";
};

/**信息获取*/

// 获取全部用户
const getListAllUserFn = async () => {
  const { data } = await getListAllUser();
  viewUserList.value = data;
};
// 获取全部公司
const getCompanyListFn = async () => {
  const { data } = await getCompanyList();
  companyList.splice(0, companyList.length, ...data);
};
// 获取全部模板
const getTemplateAllFn = async () => {
  const { data } = await getTemplateType({ id: "1820413471682985984" });
  templateAll.splice(0, companyList.length, ...data);
};
// 获取项目详情
const getProjectDetailFn = async id => {
  const { data } = await getProjectDetail({ id });
  editInitData(data);
};
/**方法 */
const deleteFA = index => {
  formData.planModels.splice(index, 1);
  fileList.value.splice(index, 1);
};

const editInitData = data => {
  data.addressed = data.provinceCode
    ? [data.provinceCode, data.cityCode, data.districtCode].filter(item => item && item.trim())
    : [];
  Object.assign(formData, data);
  console.log(data);
};

onUnmounted(() => {});
onMounted(() => {
  getCompanyListFn();
  getTemplateAllFn();
  getListAllUserFn();
  if (props.projectId) {
    getProjectDetailFn(props.projectId);
  }
});
</script>
<style lang="scss">
:deep(.user-info-dialog) {
  display: flex;
  height: 600px;
}
.user-info-dialog {
  .info-container {
    height: 580px;
  }
  .info-form {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-gap: 0 30px;
    .el-select,
    .el-cascader,
    .el-input-number,
    .el-date-editor {
      width: 100%;
    }
  }
  .all-h {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-gap: 0 30px;
    width: 100%;
    .el-select,
    .el-cascader,
    .el-input-number,
    .el-date-editor {
      width: 100%;
    }
  }
  .fan {
    .title {
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: 400;
      color: #333333;
    }
    .table {
      margin-bottom: 20px;
    }
  }
  .title {
    margin-bottom: 10px;
  }
  .form-item {
    margin: 0;
  }
}
</style>
